<?php

class Admin_ProductController extends Zend_Controller_Action
{

    private $_model = null;
    const BRAND = 9;

    public function init()
    {
        /* Initialize action controller here */
        $this->_model = new Application_Model_DbTable_Product();
    }

    public function indexAction()
    {
        $this->view->headScript()->appendFile($this->view->baseUrl("templates/admin/fancybox/jquery.mousewheel-3.0.4.pack.js"));        
        $this->view->headScript()->appendFile($this->view->baseUrl("templates/admin/fancybox/jquery.fancybox-1.3.4.pack.js"));        
        $this->view->headLink()->appendStylesheet($this->view->baseUrl("templates/admin/fancybox/jquery.fancybox-1.3.4.css"));
        
        
        // action body
        $choice = $this->_request->getParam("choice");
        if(!empty($choice)){
            $id = intval($this->_request->getParam("id"));
            $result = $this->_model->changeType($choice, $id);
            $this->_helper->json->sendJson($result);
        }
    }

    public function addAction()
    {        
        $this->view->headScript()->appendFile(
            $this->view->baseUrl("ckeditor/ckeditor.js")
        );
        $form = new Application_Form_Product();
        
        //Add list category
        $mdCat = new Application_Model_DbTable_ProductCategory();
        $select = $mdCat->select();
        $select->where("status=?",1)
               ->order("local");
        $cats = $mdCat->fetchAll($select);
        foreach($cats as $cat)
        {
            $form->category->addMultiOptions(array($cat->id=>$cat->name));
        }
        
        // Add list brand
        $mdArt = new Application_Model_DbTable_Article();
        $select = $mdArt->select();
        $select->where("article_status=?",1)
               ->where("categories_id=?",self::BRAND)
               ->order("article_local");
        $brands= $mdArt->fetchAll($select);
        foreach($brands as $brand)
        {
            $form->brand->addMultiOptions(array($brand->idarticles=>stripcslashes($brand->article_name)));
        }
        
        if($this->_request->isPost())
        {
            $code = $this->_request->getParam("code");
            $crow = $this->_model->fetchRow($this->_model->select()->where("code=?",$code));
            if($form->isValid($_POST) && !$crow)
            {
                $row = $this->_model->createRow($form->getValues());
                $row->alias = Cms_Filter_String::toAlias($row->name);
                if($form->image->isUploaded()){
                    $form->image->receive();
                    $filename = APPLICATION_PATH."/../public/images/product/".
                        basename($form->image->getFileName());
                    if(file_exists($filename)){
                        $image = new Cms_File_Image($filename);
                        $image->setDestinationPath(dirname($filename)."/thumb/");
                        $row->thumb = $image->CopyResize("350x350");
                        $row->image = $image->newname;
                    }
                }
                $row->save();
                $this->_redirect($this->view->url(array(
                    "module"=>"admin",
                    "controller"=>"product",
                    "action"=>"index"
                ),null, true));   
            }
            else
            {
                if($crow)
                {
                    $form->code->setAttrib("class","error");
                    $this->view->message = "Mã sản phẩm này đã tồn tại";
                }
                $errors = $form->getMessages();
                foreach($errors as $key=>$value){
                    $form->$key->setAttrib("class","error");
                }
            }
        }
        
        $this->view->form = $form;           
    }

    public function listAction()
    {
        // action body
        
         $sortby = $this->_request->getParam("sortby",null);
         $sorttype = $this->_request->getParam("sorttype", "asc");
         
         $parram = $this->_request->getParam("parram", null);
         $this->view->sort = array("by"=>$sortby, "type"=>$sorttype);
         
         if(!empty($parram))
         {
            $filter['name'] = $parram['keyword'];
            $filter[$parram['filter']] = 1;
         }
         
         
         
         $adapter = $this->_model->fetchPaginatorAdapter($filter,$sortby,$sorttype);
         $paginator = new Zend_Paginator($adapter);
         
         //Show 10 dòng trên 1 trang
         $paginator->setItemCountPerPage(10);
         $page = $this->_request->getParam("page",1);
         $paginator->setCurrentPageNumber($page);
         $this->view->datas = $paginator;
         
         $this->_helper->layout()->disableLayout();
         $this->getResponse()->clearBody();
    }

    public function editAction()
    {
        $this->view->headScript()->appendFile(
            $this->view->baseUrl("ckeditor/ckeditor.js")
        );
        $form = new Application_Form_Product();
        
        //Add list category
        $mdCat = new Application_Model_DbTable_ProductCategory();
        $select = $mdCat->select();
        $select->where("status=?",1)
               ->order("local");
        $cats = $mdCat->fetchAll($select);
        foreach($cats as $cat)
        {
            $form->category->addMultiOptions(array($cat->id=>$cat->name));
        }
        
        // Add list brand
        $mdArt = new Application_Model_DbTable_Article();
        $select = $mdArt->select();
        $select->where("article_status=?",1)
               ->where("categories_id=?",self::BRAND)
               ->order("article_local");
        $brands= $mdArt->fetchAll($select);
        foreach($brands as $brand)
        {
            $form->brand->addMultiOptions(array($brand->idarticles=>stripcslashes($brand->article_name)));
        }
        // lấy giá trị từ $_GET['id']
        $form->removeElement("id");
        $id = $this->_request->getParam("id");
        $row = $this->_model->find($id)->current();
        $this->view->thumb = ($row->thumb!=null)?$row->thumb:null;
        $form->populate($row->toArray());
        
        if($this->_request->isPost())
        {
            $code = $this->_request->getParam("code");
            $crow = $this->_model->fetchRow(
                $this->_model->select()->where("code=?",$code)
                                       ->where("code!=?",$row->code)
            );
            
            if($form->isValid($_POST) && !$crow)
            {
                $row->code = $form->getValue("code");
                $row->name = $form->getValue("name");
                $row->alias = Cms_Filter_String::toAlias($row->name);
                $row->category = $form->getValue("category");
                $row->brand = $form->getValue("brand");
                $row->description = $form->getValue("description");
                $row->price = $form->getValue("price");
                
                if($form->image->isUploaded()){
                    $form->image->receive();
                    $dir = $form->image->getDestination()."/";
                    $image_name = basename($form->image->getFileName());
                    $filename = $dir.$image_name;
                    
                    // Xoa hinh cu
                    if(is_file($dir.$row->image)) 
                        unlink($dir.$row->image);
                        
                    // Xoa thumb cu
                    if(is_file($dir."thumb/".$row->thumb)) 
                        unlink($dir."thumb/".$row->thumb);
                    
                    if(is_file($filename)){
                        $image = new Cms_File_Image($filename);
                        $image->setDestinationPath($dir."/thumb/");
                        $row->thumb = $image->CopyResize("300x350");
                        $row->image = $image->newname;
                    }
                }
                $row->save();
                $this->_redirect($this->view->url(array(
                    "module"=>"admin",
                    "controller"=>"product",
                    "action"=>"index"
                ),null, true));   
            }
            else
            {
                if($crow)
                {
                    $form->code->setAttrib("class","error");
                    $this->view->message = "Mã sản phẩm này đã tồn tại";
                }
                $errors = $form->getMessages();
                foreach($errors as $key=>$value){
                    $form->$key->setAttrib("class","error");
                }
            }
        }
        
        $this->view->form = $form;    
    }
    
    public function delAction()
    {
        $id = $this->_request->getParam("id", null);
        $result = null;
        if($id!=null)
        {
            $row = $this->_model->find($id)->current();
            $imagePath = APPLICATION_PATH."/../public/images/product/";
            if(is_file($imagePath."$row->image")){
                unlink($imagePath.$row->image);
            }
            $thumbPath = $imagePath."thumb/";
            if(is_file($thumbPath.$row->thumb)) {
                unlink($thumbPath.$row->thumb);
            }
            $result = $row->delete();
        }
        $this->_helper->json->sendJson($result);
    }

}













